/**********************************************************************************
 * * File:		zigbee_test.c
 * * Author:	jack
 * * Team:		Farsight
 * * Version:	V0.1
 * * Date:		2017.1.1
 * * Brief:		ZigBee Send and Recive Programs
 * ********************************************************************************
 * ********************************************************************************
 * * History:
 * * 2013.07.11:  V0.1		Fisrt version
 * ********************************************************************************/

#include "zigbee.h"
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <time.h>
#include <termios.h>
#include "ddebug.h"
#include <sys/ipc.h>
#include <sys/sem.h>
static int fd_zigbee;
//static int semid;
int serial_init_a9(char * tty_zigbee)
{ 

//	int key2;
	//fd_zigbee = open("/dev/ttyUSB0", O_RDWR);
	//int fd_zigbee = open(tty_zigbee, O_RDWR);
	fd_zigbee = open(tty_zigbee, O_RDWR);

	if(fd_zigbee < 0)
	{
		DDEBUG(P_URGENCY,"<<ZIGBEE_RW>> open ttyUSB error.");
		return -1;
	}

/*	if((key2 = ftok("/app", 'i')) < 0)
	{
		syserr("ftok");
		return -1;
	}

	if((semid  = semget(key2, 1, 0666|IPC_CREAT)) < 0)
	{
		syserr("semget");
		exit(1);
	}
	
	DDEBUG(P_NORMAL,"<<ZIGBEE_RW>> get semid:%d\n",semid);
*/
//	semctl(semid, 1, SETVAL, 1);
//	semctl(semid, 2, SETVAL, 1);
	struct termios options;

	tcgetattr(fd_zigbee, &options);
	options.c_cflag |= (CLOCAL | CREAD);
	options.c_cflag &= ~CSIZE;
	options.c_cflag &= ~CRTSCTS;   
//	options.c_cflag &= ~PARENB;   
	options.c_cflag |= CS8;
	options.c_cflag &= ~CSTOPB;              
	options.c_iflag |= IGNPAR;
	options.c_iflag &= ~(ICRNL | IXON );
	options.c_oflag = 0;
	options.c_lflag = 0;

	cfsetispeed(&options, B115200);
	cfsetospeed(&options, B115200);

	tcsetattr(fd_zigbee, TCSANOW, &options);

	return fd_zigbee;
}


int write_zigbee_a9(int fdd_zigbee,char * write_buf,int length)
{
	int ret;
	if(fd_zigbee < 0)
		return -1;
//	struct sembuf P = {1, -1, 0};
//	semop(semid, &P, 1);
	ret = write(fd_zigbee, write_buf, length);
	if(ret < 0)
		DDEBUG(P_NORMAL,"<<ZIGBEE_RW>> write error\n");
//	struct sembuf V = {1, 1, 0};
//	semop(semid, &V, 1);
	DDEBUG(P_NORMAL,"<<ZIGBEE_RW>> send to %d num %d\n",fd_zigbee,ret);
	return 0;

}

int read_zigbee_a9(int fdd_zigbee,char * read_buf,int length)
{
	int ret;
	if(fd_zigbee < 0)
		return -1;
//	struct sembuf P = {2, -1, 0};
//	semop(semid, &P, 1);
	ret = read(fd_zigbee, read_buf, length);
	if(ret < 0)
		DDEBUG(P_NORMAL,"<<ZIGBEE_RW>> read error\n");
//	struct sembuf V = {2, 1, 0};
//	semop(semid, &V, 1);
	DDEBUG(P_NORMAL,"<<ZIGBEE_RW>> read from %d num %d\n",fd_zigbee, ret);
	return 0;

}

int serial_exit_a9(int fdd_zigbee)
{
	if(fd_zigbee < 0)
		return -1;
	close(fd_zigbee);
	return 0;
}

